package ua.epam.muzalevskiy.traction.commands;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ua.epam.muzalevskiy.traction.configuretion.MessageConfigurer;
import ua.epam.muzalevskiy.traction.configuretion.PagePathConfigurer;
import ua.epam.muzalevskiy.traction.dao.DaoFactory;
import ua.epam.muzalevskiy.traction.dao.VehicleDao;
import ua.epam.muzalevskiy.traction.dao.exceptions.DatabaseException;
import ua.epam.muzalevskiy.traction.dao.exceptions.NotExistsParameterException;

/**
 * <code>AddVehicleToRouteCommand</code> class is the <code>Command</code> 
 * interface implementation, that realized <code>Command</code> pattern. 
 * Current class encapsulate action of adding vehicle with entered ID to 
 * required route.
 *
 * @author Muzalevskiy Vitaliy
 * @see Command
 * @see Route
 * @see Vehicle
 * @see VehicleDao
 */
public class AddVehicleToRouteCommand implements Command {
    private static DaoFactory factory = new DaoFactory();
    private VehicleDao vehicleDao = factory.getVehicleDao();
    private static final String PARAM_NAME_VEHICLE_ID = "vehicle_id";
    private static final String PARAM_NAME_ROUTE_ID = "route_id";
    

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String page;
        try {
            int vehicleID = Integer.valueOf(request.getParameter(PARAM_NAME_VEHICLE_ID));
            int routeID = Integer.valueOf(request.getParameter(PARAM_NAME_ROUTE_ID));
            vehicleDao.assigneToRoute(vehicleID, routeID);
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ADMINISTRATION_PAGE);
        } catch (NotExistsParameterException ex) {
            request.setAttribute(Command.ATTRIBUTE_NAME_ERROR_MESSAGE, 
                    MessageConfigurer.getInstance()
                    .getProperty(MessageConfigurer.ASSIGNE_VEHICLE_TO_ROUTE_ERROR_MESSAGE));
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ERROR_PAGE);
        } catch (DatabaseException e){
            request.setAttribute(Command.ATTRIBUTE_NAME_ERROR_MESSAGE, 
                    MessageConfigurer.getInstance()
                    .getProperty(MessageConfigurer.NOT_CONNECTED_VEHICLE_AND_ROUTE_ERROR_MESSAGE));
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ERROR_PAGE);
        }
        return page;
    }
    
}
